// @Author EthanScriptOn
// @Desc
package config_source_loader

import (
	"errors"
	"gitee.com/fatzeng/srf_switch_basic_components/util"
	"gitee.com/fatzeng/srf_switch_config/config_define"
)

type EnvVariableSourceLoader struct {
	*ArgsBaseSourceLoader
}

func (e *EnvVariableSourceLoader) ShouldExecute(checkerInstance interface{}) (bool, error) {
	shouldExecute, err := e.ArgsBaseSourceLoader.ShouldExecute(checkerInstance)
	if err != nil || !shouldExecute {
		return shouldExecute, err
	}
	if !e.ctx.IsOpenEnv() {
		return false, errors.New("the env variable configuration parsing function is not enabled")
	}
	return true, nil
}

func (e *EnvVariableSourceLoader) Initialization() (err error) {
	keyValuePairsSlicing := GenerateSourceLoaderSlicing("=", true, 2)
	multiKeySlicing := GenerateSourceLoaderSlicing(".", true, -1)
	e.ConfigSourceLoaderSteps, err = GenerateAllowableCutFileBaseSourceLoaderSteps(e, keyValuePairsSlicing, multiKeySlicing, `(\\w+)\\[(\\d+)\\]`)
	if err != nil {
		return err
	}
	e.ArgsBaseSourceLoader, err = GenerateArgsBaseSourceLoader(e, e.GetConfigSourceType())
	if err != nil {
		return err
	}
	return e.ArgsBaseSourceLoader.Initialization()
}

func (e *EnvVariableSourceLoader) GetConfigSourceType() config_define.ConfigSourceType {
	return config_define.ENV
}

func (e *EnvVariableSourceLoader) LoadConfigSource() (interface{}, error) {
	sourceLoaderResult := new(SourceLoaderResult)
	sourceLoaderResult.SetConfigSourceType(e.GetConfigSourceType())
	envLoadData := util.EnvArgsLoad()
	loadNodes, err := e.ArgsBaseSourceLoader.LoadSourceLoaderNodes(e.ArgsBaseSourceLoader.ConvertToLine(envLoadData))
	if err != nil {
		return nil, err
	}
	if err = e.ArgsBaseSourceLoader.PerfectSourceLoaderResultWithSegmentInformation(sourceLoaderResult, loadNodes); err != nil {
		return nil, err
	}
	return sourceLoaderResult, nil
}
